package com.bbznb.service.serviceImpl;

import com.bbznb.entity.UserRegister;
import com.bbznb.entity.UserUse;
import com.bbznb.mapper.LoginMapper;
import com.bbznb.service.LoginService;
import com.bbznb.util.JwtUtil;
import com.bbznb.util.UserToken;
import com.bbznb.util.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.concurrent.TimeUnit;

import static com.bbznb.common.UserS.USER_LOGIN;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    LoginMapper loginMapper;
    @Override
    public UserToken login(String username, String password) {
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        UserUse userUse =  loginMapper.login(username, password);
        if(userUse == null){
            throw  new RuntimeException("用户名或密码错误");
        }

        String token = JwtUtil.generateToken(username);
        User user = new User();
        user.setId(userUse.getUserId());
        user.setUsername(username);
        user.setPassword(password);
        UserToken userToken = new UserToken();
        userToken.setUser(user);
        userToken.setToken(token);
        redisTemplate.opsForValue().set(USER_LOGIN,username,30, TimeUnit.MINUTES);
        return userToken;
    }


    @Transactional
    @Override
    public void register(UserRegister userRegister) {
        userRegister.setPassword(DigestUtils.md5DigestAsHex(userRegister.getPassword().getBytes()));
         loginMapper.register(userRegister);
         loginMapper.register_data(userRegister);
    }
}
